﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Quickly.Certs.AliDns
{
    public class AlibabaCloudDnsClient
    {
        protected readonly IOptionsMonitor<AlibabaCloudAccessKey> _accessKey;
        protected readonly IOptionsMonitor<AlibabaCloudEndpoint> _endpoint;
        protected readonly ILogger _logger;

        public AlibabaCloudDnsClient(
            IOptionsMonitor<AlibabaCloudAccessKey> accessKey,
            IOptionsMonitor<AlibabaCloudEndpoint> endpoint,
            ILogger<AlibabaCloudDnsClient> logger)
        {
            _endpoint = endpoint;
            _accessKey = accessKey;
            _logger = logger;
        }

        public AlibabaCloud.SDK.Alidns20150109.Client Client => GetClient(_accessKey.CurrentValue, _endpoint.CurrentValue);

        static AlibabaCloud.SDK.Alidns20150109.Client GetClient(AlibabaCloudAccessKey accessKey, AlibabaCloudEndpoint endpoint)
        {
            var config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = accessKey.AccessKeyId,
                AccessKeySecret = accessKey.AccessKeySecret,
                Endpoint = endpoint.Address,
            };

            return new AlibabaCloud.SDK.Alidns20150109.Client(config);
        }

        public async Task<string?> AddDomainRecordAsync(string domain, string rr, string type, string value, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var request = new AlibabaCloud.SDK.Alidns20150109.Models.AddDomainRecordRequest
            {
                DomainName = domain,
                RR = rr,
                Type = type,
                Value = value
            };

            var resp = await Client.AddDomainRecordAsync(request);

            _logger.LogInformation("Received [AddDomainRecord] {RequestId}: {@Response}", resp.Body.RequestId, resp);

            if (resp.StatusCode == 200)
            {
                return resp.Body.RecordId;
            }

            return null;
        }

        public async Task<string?> DeleteDomainRecordAsync(string recordId, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var resp = await Client.DeleteDomainRecordAsync(new AlibabaCloud.SDK.Alidns20150109.Models.DeleteDomainRecordRequest
            {
                RecordId = recordId,
            });

            _logger.LogInformation("Received [DeleteDomainRecord] {RequestId}: {@Response}", resp.Body.RequestId, resp);

            if (resp.StatusCode == 200)
            {
                return resp.Body.RecordId;
            }

            return null;
        }
    }
}
